'''
京彩一生防癌医疗保险
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, time
from common.helper import Helper
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "京彩一生防癌医疗保险"
    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(0, 71)],
            # 有无社保
            "socialSec": ["Y", "N"],
            # 保障期限
            "expire": ["1年"],
            # 特定疾病特需治疗 0 不勾选 1 勾选
            "specialDisease": ["0", "1"],
            # 扩展质子重离子（可选）	0 不勾选 1 勾选
            "ext_import": ["0", "1"]
        }
        for v in product(plan["year"], plan["socialSec"], plan["expire"], plan["specialDisease"], plan["ext_import"]):
            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4]
            ))
            self.mysql._conn.commit()

            print(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4]
            ))

    # 执行爬虫
    def requestJson(self, dt=None):

        if 0 <= int(dt["year"]) <= 5:

            ageTo = 5

            ageFrom = 0

        elif 6 <= int(dt["year"]) <= 10:
            ageTo = 10

            ageFrom = 6
        elif 11 <= int(dt["year"]) <= 15:

            ageTo = 15

            ageFrom = 11

        elif 16 <= int(dt["year"]) <= 20:

            ageTo = 20

            ageFrom = 16

        elif 21 <= int(dt["year"]) <= 25:

            ageTo = 25

            ageFrom = 21

        elif 26 <= int(dt["year"]) <= 30:

            ageTo = 30

            ageFrom = 26

        elif 31 <= int(dt["year"]) <= 35:

            ageTo = 35
            ageFrom = 31
        elif 36 <= int(dt["year"]) <= 40:

            ageTo = 40
            ageFrom = 36
        elif 41 <= int(dt["year"]) <= 45:

            ageTo = 45
            ageFrom = 41

        elif 46 <= int(dt["year"]) <= 50:

            ageTo = 50
            ageFrom = 46

        elif 51 <= int(dt["year"]) <= 55:

            ageTo = 55
            ageFrom = 51

        elif 56 <= int(dt["year"]) <= 60:

            ageTo = 60
            ageFrom = 56

        elif 61 <= int(dt["year"]) <= 65:

            ageTo = 65
            ageFrom = 61
        else:

            ageTo = 70
            ageFrom = 66

        brand = {
            "ageFrom": ageFrom,
            "ageTo": ageTo
        }

        if dt["ext_import"] == "0" and dt["specialDisease"] == "0":

            plan = "标准款"

            if dt["socialSec"] == "Y":

                socialSec = "JJDAFA(SI)"

            else:

                socialSec = "JJDAFA(NSI)"


        elif dt["specialDisease"] == "1" and dt["ext_import"] == "0":

            plan = "特需板"

            if dt["socialSec"] == "Y":

                socialSec = "JJDAFA(SI)(T)"

            else:

                socialSec = "JJDAFA(NSI)(T)"

        elif dt["specialDisease"] == "0" and dt["ext_import"] == "1":

            plan = "质子重离子版"

            if dt["socialSec"] == "Y":
                socialSec = "JJDAFA(SI)(Z)"

            else:

                socialSec = "JJDAFA(NSI)(Z)"

        else:

            plan = "特需＋质子重离子版"

            if dt["socialSec"] == "Y":
                socialSec = "JJDAFA(SI)(T)(Z)"

            else:

                socialSec = "JJDAFA(NSI)(T)(Z)"

        data = {"ageLimit": {"ageTo": brand["ageTo"], "ageFrom": brand["ageFrom"]},
                "dayLimit": {"dayTo": "366", "dayFrom": "366"},
                "planCode": socialSec, "planName": plan,
                "productCode": "HET-CANCAR",
                "productName": "京彩一生防癌医疗保险", "day": "366"}

        payload = json.dumps(data)

        r = requests.post(url=domain[self.name]["url"] + str(int(time.time()) * 1000),
                          headers=domain[self.name]["header"], data=payload)

        if r.status_code == 200 and r.json()["status"]:

            price = Helper.decimalParse( r.json()["premium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {

                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("/*更新产品价格信息失败:%d*/"%dt["id"])\

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)


